import {
	getTokenLocal,
	setTokenLocal,
	removeTokenLocal,
	getUserLocal,
	setUserLocal
} from '@/utils/auth'

import * as UserAPI from '@/api/user'

const getDefaultState = () => {
	return {
		token: getTokenLocal(),
		user: getUserLocal(),
		avatar: "",
	}
}

const state = {
	token: "",
	user: {},
	avatar: "",
};

const getters = {
	getToken: (state) => state.token,
	getUser: (state) => state.user,
	getAvatar: (state) => state.avatar,
};


const mutations = {
	setToken(state, token) {
		state.token = token;
		setTokenLocal(token);
	},
	setUser(state, user) {
		state.user = user;
		setUserLocal(user);
	},
	setAvatar(state, avatar) {
		state.avatar = avatar;
	},

	resetState: (state) => {
		Object.assign(state, getDefaultState())
	},
};

// 重置token 即重置过期时间  还没有完工 ...
const actions = {
	// user login
	login({commit}, userInfo) {
		const {
			name,
			password
		} = userInfo
		return new Promise((resolve, reject) => {
			UserAPI.login({
				name: name.trim(),
				password: password
			}).then(result => {
				const {
					data
				} = result
				commit('setToken', data.token);
				commit('setUser', data.user);
				resolve();
			}).catch(error => {
				reject(error);
			})
		})
	},

	// get user info
	async getInfo({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			let id = state.user.id;
			UserAPI.getDetailById(id).then(result => {
				const {
					data
				} = result;
				if (!data) {
					return reject('获取用户数据失败，请重新登录')
				}
				const {
					avatar
				} = data;
				commit('setAvatar', avatar);
				resolve();
			}).catch(error => {
				reject(error)
			})
		})
	},

	// user logout
	logout({
		commit
	}) {
		return new Promise((resolve, reject) => {
			UserAPI.logout().then(() => {
				removeTokenLocal() // must remove  token  first
				// resetRouter()
				commit('resetState')
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},

	// remove token
	resetToken({
		commit
	}) {
		return new Promise(resolve => {
			removeTokenLocal() // must remove  token  first
			commit('resetState')
			resolve()
		})
	}
};

export default {
	namespaced: true,
	state,
	getters,
	mutations,
	actions,
};
